package com.wswy.wzcx.ui.module.feedback

import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AlertDialog
import com.che.libcommon.api.BaseResult
import com.che.libcommon.api.ProgressDialogObserver
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.model.DataCenter
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.utils.ImageUtils
import com.wswy.wzcx.utils.RxUtils
import io.reactivex.Single
import kotlinx.android.synthetic.main.fragment_add_feedback.*

/**
 * 添加反馈
 */
class AddFeedbackFragment : CBaseFragment() {


    private companion object {

        private val types = arrayOf(FeedbackType(1,"违章报错"),
                FeedbackType(2,"违章代办"),
                FeedbackType(3,"罚单缴费"),
                FeedbackType(4,"支付问题"),
                FeedbackType(5,"退款问题"),
                FeedbackType(6,"软件报错"),
                FeedbackType(7,"功能建议"),
                FeedbackType(8,"其他类型"))

    }


    override fun getFragmentTitle(): String {
        return "意见反馈"
    }

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_add_feedback
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        fbl_photo_container.maxImages = 6
        fbl_photo_container.attachedFragment = this


        group_titles.setOnClickListener {
            chooseTypes{

                lastFeedbackType = it

                lastFeedbackType?.let {
                    tv_feed_type.text = it.name
                }

            }
        }

        btn_submit.setOnClickListener {
            doSubmit()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        fbl_photo_container?.onActivityResult(requestCode, resultCode, data)
    }


    private var lastType = 0
    private var lastFeedbackType:FeedbackType?=null
    private fun chooseTypes(block:((FeedbackType?)->Unit)){

        val list = types.map { it.name }.toTypedArray()
        val out = IntArray(1)
        out[0] = lastType

        AlertDialog.Builder(requireContext()).apply {

            setTitle("选择问题类型")
            setSingleChoiceItems(list,out[0]){ _, which ->
                out[0]=which
            }

            setPositiveButton(R.string.ok) { dialog, _ ->

                lastType = out[0]
                block.invoke(types[out[0]])
                dialog.dismiss()
            }

            setNegativeButton(R.string.cancel) { dialog, _ ->

                dialog.dismiss()
            }

        }.run {
            show()
        }
    }

    private fun doSubmit(){

        if (!DataCenter.get().hasLogin()){
            ToastUtils.showText("请先登录")
            return
        }

        val type = lastFeedbackType

        if (type == null){
            ToastUtils.showText("请选择问题反馈类型")
            return
        }

        val content = et_desc.text?.trim()?.toString()

        if (content.isNullOrEmpty()){
            ToastUtils.showText("写点什么吧~")

            return
        }

        val files = fbl_photo_container.getFiles()

        Single.fromCallable {

            val f = files.map {
                if (it.extension == "gif"){
                    it
                }else{
                    ImageUtils.compress(it.absolutePath).absoluteFile
                }
            }.associateBy {
                it.absolutePath
            }
            return@fromCallable if (f.isNotEmpty()){
                val result = kotlin.runCatching {
                    Api.get().uploadFiles(null,f).blockingGet().values.map { it.objectKey }.filterNotNull().joinToString(separator=",")
                }
                result.getOrDefault("")
            }else{
                ""
            }
        }.flatMap {
            Api.get().submitFeedback(type.type,content,it)
        }.compose(RxUtils.io2main()).subscribe(object :ProgressDialogObserver<Any?>(context){
            override fun onApiResult(t: Any?) {
                ToastUtils.showText("提交成功")
                finish()
            }

            override fun onApiError(result: BaseResult<*>?) {
                toastErrorMsg(result)
            }

        })

//        Single.create<List<File>> { it ->
//            val ret = arrayListOf<File>()
//
//            files.map {
//                //gif
//                if (it.extension == "gif"){
//                    it
//                }else{
//                    ImageUtils.compress(it.absolutePath).absoluteFile
//                }
//            }.run {
//                ret.addAll(this)
//            }
//            it.onSuccess(ret)
//        }.compose(RxUtils.switch2io())
//                .map {
//
//                    if (it.isNotEmpty()){
//
//                        val f = it.associateBy { it.path }
//
//                        Api.get().uploadFiles(null,f).blockingGet()
//                    }else{
//                        Collections.emptyMap<String,File>()
//                    }
//
//                }
//
//        Api.get().submitFeedback(type.type,content).subscribe(object :ProgressDialogObserver<Any?>(context){
//            override fun onApiResult(t: Any?) {
//                ToastUtils.showText("提交成功")
//                finish()
//            }
//
//            override fun onApiError(result: BaseResult<*>?) {
//                toastErrorMsg(result)
//            }
//
//        })
    }

}